Chapter 14: Exercises

  1. What is the data type return by each of the following MATLAB statement?
    1. class(eye(3))
    2. class(rand(4)>0)
  2. 給定一實數矩陣 A,請寫一列 MATLAB 敘述,將其所有非正元素設定成零。

    Solution:

    A(A<=0)=0;
  3. 給定一實數矩陣 A,請寫一列 MATLAB 敘述,將其所有零元素設定成 nan。

    Solution:

    A(A==0)=nan;
  4. 給定一實數矩陣 A,請寫一列 MATLAB 敘述,將其所有 nan 元素設定成零。
    Hint: Use "isnan".

    Solution:

    A(isnan(A))=0;
  5. 給定一實數矩陣 A,請寫一列 MATLAB 敘述,列出所有介於 7 和 11 之間的的元素,

    Solution:

    A(7<A & A<11)
  6. 給定一實數和複數交錯的矩陣 A,請寫 MATLAB 一列敘述,將其所有複數元素設定成 nan。
    Hint: Use "imag" to extract the imaginary part of a matrix.

    Solution:

    A(~(imag(A)==0))=nan;
  7. 請排列下列數學運算元的優先順序:
    1. 負號(-)
    2. 元素左除(.\)
    3. 共軛轉置(')
    4. 加法(+)
    5. 冒號(:),例如 x=1:2:10
    Ans: 優先順序: c>a>b>d>e
  8. What are the values returned by the following expressions?
    1. bitor(10,2)
    2. bitand(10,2)
    3. bitshift(10,2)
    4. bitxor(10,2)
  9. 執行下列程式碼後,請問變數 a, b, c, d, e 的值各是多少? x=[2 4 6 8 10]; y=[1 2 3 4 5 ]; a=union(x, y); b=intersect(x, y); c=setdiff(x, y); d=setdiff(y, x); e=setxor(x, y);
  10. 請寫一列 MATLAB 敘述,產生元素值為 0 或 1 的向量,向量長度為 100,出現 0 或 1 的位置由亂數決定,而且
    1. 0 和 1 的個數大約各佔一半。
      Hint: Use "rand", "randn", or "randi".
    2. 0 和 1 的個數剛好各佔一半。
      Hint: Use "randperm".
  11. Suppose that x={'circle', 'diamond', 'line'}; y={'circle', 'square'}; What is the value returned by each of the following MATLAB commands?
    1. union(x, y)
    2. intersect(x, y)
    3. setdiff(x, y)
    4. setxor(x, y)
    5. unique([x, y])
    6. ismember('square', y)
  12. Let's execute the following script a=rand(1,100)>0.5; b=rand(1,100)>0.5; c=bitxor(bitxor(a,b), b); d=~bitxor(~bitxor(a,b), b); isequal(a, c) isequal(a, d)
    1. Explain why a is equal to c.
    2. Explain why a is equal to d.
  13. 假設一矩陣 A 可表示如下: $$ A= \left[ \begin{matrix} 0.3 & 0.1 & 0.2\\ 0.2 & 0.7 & 0.4\\ 0.5 & 0.2 & 0.4\\ \end{matrix} \right] $$ 請寫一個 MATLAB 程式找出最小的 正整數 $n$ 值,使得 $A^{n+1}=A^n$ 。此時 $n$ 值為何?

MATLAB程式設計:入門篇